/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author nekdo
 */
@Stateless
public class AircraftDao implements AircraftDaoLocal {

    @PersistenceContext
    private EntityManager em;

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public EntityManager getEm() {
        return em;
    }

    
    @Override
    public void create(Aircraft aircraft) {
        if(aircraft == null) throw new IllegalArgumentException("aircraft is null");
        if(aircraft.getId() != null) throw new IllegalArgumentException("id already set");
        
        try {
            em.persist(aircraft);
        } catch(Exception ex) {
            throw new ServiceFailureException(ex);
        }
    }

    @Override
    public Aircraft get(Long id) {
        if(id == null) throw new IllegalArgumentException("id is null");
        Aircraft aircraft;
        
        try {
            aircraft = em.find(Aircraft.class, id);
        } catch(Exception ex) {
            throw new ServiceFailureException(ex);
        }
        return aircraft;
    }

    @Override
    public void update(Aircraft aircraft) {
        if(aircraft == null) throw new IllegalArgumentException("aircraft is null");
        if(aircraft.getId() == null) throw new IllegalArgumentException("id is null");
        
        try {
            em.merge(aircraft);
        } catch(Exception ex) {
            throw new ServiceFailureException(ex);
        }
    }

    @Override
    public void remove(Aircraft aircraft) {
        if(aircraft == null) throw new IllegalArgumentException("aircraft is null");
        if(aircraft.getId() == null) throw new IllegalArgumentException("id is null");
        
        try {
            em.remove(em.find(Aircraft.class, aircraft.getId()));
        } catch(Exception ex) {
            throw new ServiceFailureException(ex);
        }
    }

    @Override
    public List<Aircraft> findAll() {
        Query q = em.createQuery("SELECT a FROM Aircraft AS a");
        List<Aircraft> res = (List<Aircraft>)q.getResultList();

        return res;
    }

    @Override
    public Aircraft findByCode(String code) {
        if (code == null || code.equals(""))
            throw new IllegalArgumentException("code null or empty");
        
        Query q = em.createQuery("SELECT a FROM Aircraft AS a WHERE a.code = :code");
        q.setParameter("code", code);
        Aircraft res = (Aircraft)q.getSingleResult();

        return res;        
    }
    
    
}

